package org.bookie.init.tasks;

import java.util.Properties;

import org.apache.hivemind.Registry;
import org.bookie.init.InitTask;
import org.bookie.model.Bet;
import org.bookie.model.BetSlip;
import org.bookie.model.Outcome;
import org.bookie.model.SingleBetSlip;
import org.bookie.model.User;
import org.bookie.model.Wager;
import org.bookie.model.services.BetDAO;
import org.bookie.model.services.BetSlipDAO;
import org.bookie.model.services.UserDAO;

public class BetSlipLoad implements InitTask {

	private boolean empty;

	public Properties check(Registry registry) throws Exception {
		Properties result = new Properties();
		UserDAO userDAO = (UserDAO) registry.getService(UserDAO.class);
		User user = userDAO.findByEmail(UserLoad.HOMER_EMAIL);
		if(user==null){
			result.put("ERROR!!!", "Please run UserLoad first");
		}
		BetDAO betDAO = (BetDAO)registry.getService(BetDAO.class);
		Bet bet = (Bet) betDAO.findExpired().get(0);
		if(bet==null){
			result.put("ERROR!!!", "Please run EventLoad first");
		}
		empty = user.getBetSlips().isEmpty();
		result.put("User '"+user.getEmail()+"' has bet slips", String.valueOf(!empty));
		return result;
	}

	public Properties execute(Registry registry) throws Exception {
		Properties result = new Properties();
		UserDAO userDAO = (UserDAO) registry.getService(UserDAO.class);
		BetSlipDAO betSlipDAO = (BetSlipDAO)registry.getService(BetSlipDAO.class);
		BetDAO betDAO = (BetDAO)registry.getService(BetDAO.class);
		if(empty){
			User user = userDAO.findByEmail(UserLoad.HOMER_EMAIL);
			BetSlip bs = new SingleBetSlip(user, new Double(10));
			Bet bet = (Bet) betDAO.findExpired().get(0);
			Outcome outcome = bet.getOutcomes().get(0);
			bs.addBet(new Wager(outcome));
			betSlipDAO.makePersistent(bs);
			result.put("User '"+user.getEmail()+"' placed bet", outcome.getLabel());
		} else {
			result.put("Update", "Skipped");
		}
		return result;
	}

	public String getTitle() {
		return "Loading bet slips";
	}

}
